/*
 * 创建日期 2009-12-18
 *
 * 成都天和软件公司
 * 电话：028-85425861
 * 传真：028-85425861-8008
 * 邮编：610041 
 * 版权所有
 */
package  org.fantasy.common.grid.part;

import  org.fantasy.common.grid.bean.Column;
import  org.fantasy.common.grid.bean.ReportParam;
import  org.fantasy.common.grid.bean.ScriptContext;
import  org.fantasy.common.grid.bean.Toolbar;
import  org.fantasy.common.grid.util.GridConst;
import  org.fantasy.common.util.StringUtil;
import  org.fantasy.common.util.WebUtil;

import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

/**
 *  基本菜单栏
 * @author: 王文成
 * @version: 1.0
 * @since 2009-12-18
 */
public abstract class BaseReportPart implements Part {

    protected ReportParam param;

    protected HttpServletRequest request;
    
    protected ScriptContext context;

    public BaseReportPart(ReportParam param, HttpServletRequest request) {
        this.param = param;
        this.request = request;
        this.context = new ScriptContext(request,param);
    }

    /**
     * 工具条
     * 
     * @return
     */
    public StringBuffer getToolBar() {
        StringBuffer html = new StringBuffer(1024);
        html.append(getMenuBar());
        html.append(getColSelect());
        return html;
    }

    /**
     * 工具条
     * 
     * @return
     */
    protected StringBuffer getMenuBar() {
        Toolbar bar = param.getToolbar();
        Set<String> buttons = bar.getButtons();
        StringBuffer html = new StringBuffer(1024);
        html.append("<div class=\"toolbar\"> \n");
        if (buttons.contains(Toolbar.BUTTON_COL)) {
            html.append("   <a name=\"SelectCols\" href=\"javascript:void(0)\" class=\"lbutton\">显示/隐藏 列</a>  \n");
            html.append("   <span class=\"lseparator\"></span>  \n");
        }
        if (buttons.contains(Toolbar.BUTTON_BACK)) {
            html.append("   <a href=\"javascript:history.back();\" class=\"lbutton\"> 后 退 </a>  \n");
            html.append("   <span class=\"lseparator\"></span> \n");
        }
        if (buttons.contains(Toolbar.BUTTON_FORWARD)) {
            html.append("   <a href=\"javascript:history.forward();\" class=\"lbutton\"> 前 进 </a>  \n");
            html.append("   <span class=\"lseparator\"></span>  \n");
        }

        if (buttons.contains(Toolbar.BUTTON_EXPORT)) {
            html.append("   <a href=\"javascript:" + param.getVar() + ".Export();\" class=\"rbutton\"> 导 出 </a> \n");
            html.append("   <span class=\"rseparator\"></span> \n");
        }
        html.append("</div> \n");
        return html;
    }

    /**
     * 取得选择列
     * 
     * @return
     */
    protected StringBuffer getColSelect() {
        Toolbar bar = param.getToolbar();
        Set<String> buttons = bar.getButtons();
        if( !buttons.contains(Toolbar.BUTTON_COL) )
            return new StringBuffer(0);
        
        StringBuffer html = new StringBuffer(1024);
        List<Column> heads = param.getTableHeads().get(0);
        StringBuffer rows = new StringBuffer(1024);
        int count = 0;
        for (Column col : heads) {
            boolean isShow = !"false".equalsIgnoreCase(col.getVisible());
            if (isShow && !col.isDetailType()) {
                count++;
                String checked = param.isHideCol(col) ? "" : " checked=\"checked\"";
                rows.append("           <tr> \n");
                rows.append("               <td class='ndcol1'><input type='checkbox' value='" + col.getDesc() + "'"
                        + checked + "></td> \n");
                rows.append("               <td class='ndcol2'>" + col.getFieldLabel() + "</td > \n");
                rows.append("           </tr> \n");
            }
        }
        int height = (count * 28 > 400 ? 400 : count * 28);
        html.append("   <div class=\"colselect\" style='height:" + height + "px'> \n");
        html.append("   <table border=\"0\" cellSpacing=\"0\" cellPadding=\"0\"> \n");
        html.append("       <tbody> \n");
        html.append(rows);
        html.append("       </tbody> \n");
        html.append("   </table> \n");
        html.append("   </div> \n");
        return html;
    }

    /**
     * 排序
     * 
     * @return
     */
    protected StringBuffer getSortSelect() {
        StringBuffer html = new StringBuffer(1024);
        return html;
    }

    /**
     * 图表
     * 
     * @return
     */
    protected StringBuffer getChart() {
        StringBuffer html = new StringBuffer(1024);
        return html;
    }

    /**
     * 取得分页脚本
     * 
     * @return
     */
    public StringBuffer getPager() {
        List dataList = param.getDataList();
        String action = param.getAction();
        StringBuffer html = new StringBuffer(1024);
        String empty = new String();
        String pageStart = (String) WebUtil.findAttribute(request, GridConst.PAGE_START, empty);
        String pageSize = (String) WebUtil.findAttribute(request, GridConst.PAGE_SIZE, empty);
        String pageCount = (String) WebUtil.findAttribute(request, GridConst.PAGE_COUNT, empty);
        if (param.isPage()) {
            html.append("<tr><td height=\"20px\" align='right'>\n");
            if (StringUtil.isValid(pageCount) || dataList.isEmpty()) {
                html.append("<input type='hidden' name='pageStart' value='" + pageStart + "'/>\n ");
                html.append("<input type='hidden' name='pageSize' value='" + pageSize + "'/>\n ");
                html.append("<input type='hidden' name='pageCount' value='" + pageCount + "'/>\n ");
            } else {
                html.append("<input type='hidden' name='pageStart' value='1'/>\n ");
                html.append("<input type='hidden' name='pageSize' value='" + dataList.size() + "'/>\n ");
                html.append("<input type='hidden' name='pageCount' value='" + dataList.size() + "'/>\n ");
            }

            html.append("<div align='right' class='grey' id=\"initpage\"></div>\n ");
            html.append("<input type='hidden' value='yes' name='pagination'/>\n ");
            html.append("<script type='text/javascript'>\n ");
            html.append("var myPage = new page();\n ");
            html.append("myPage.init(document.forms[0].name, 'pageStart', 'pageSize','pageCount',document.getElementById('initpage'));\n");
            html.append("myPage.printPageCode('yes');\n ");
            String ctx = request.getContextPath();
            if (action.startsWith("/"))
                action = ctx + action;

            html.append("document.forms[0].action='" + action + "';\n");
            html.append("</script>\r\n ");
            html.append("</td></tr>\n");
        }
        return html;
    }

    /**
     * 取得报表脚本
     * 
     * @return
     */
    public StringBuffer getScript() {
        String id = context.getId();
        String var = context.getVar();
        String ctx = request.getContextPath();
        String pagerVar = context.getPagerVar();
        StringBuffer html = new StringBuffer(512);
        html.append("<script type=\"text/javascript\" src='" + ctx + "/js/grid.js'></script>\n");
        html.append("<script type=\"text/javascript\"> \n");
        html.append("(function(){ \n");
        html.append("   var _PARAM = {}; \n");
        html.append("   _PARAM.tableID = '" + id + "'; \n");
        html.append("   _PARAM.tableConfig = '" + context.getTableConfig() + "'; \n");
        html.append("   _PARAM.isRowsSelect = true; \n");
        html.append("   _PARAM.isRowsHover = true; \n");
        html.append("   _PARAM.isHeadHover = true; \n");
        html.append("   _PARAM.isSortable = true; \n");
        html.append("   _PARAM.isHideCols = true; \n");
        html.append("   window['" + var + "'] = GridUtil.createReport(_PARAM);\n");
        html.append("   window['" + var + "'].lockHead(" + param.isLockHead() + ");\n");
        html.append("   window['" + var + "'].Export = function(){  \n");
        html.append("       var pager = window['" + pagerVar + "']; \n");
        html.append("       if( pager.isComplete() ){\n");
        html.append("           if( pager.getCount() == 0 ) return; \n");
        html.append("           var OPTION = {};  \n");
        html.append("           OPTION.count = pager.getCount();  \n");
        html.append("           OPTION.win = window;  \n");
        html.append("           OPTION.sql = document.getElementById('" + context.getSqlId() + "').value;  \n");
        html.append("           OPTION.param = document.getElementById('" + context.getTagParamId() + "').value;  \n");
        html.append("           GridUtil.initExport(OPTION);  \n");
        html.append("       }else{ \n");
        html.append("           Message.alert('正在加载查询信息，请稍候.....'); \n");
        html.append("       } \n");
        html.append("   }  \n");
        html.append("})();\n");
        html.append("</script> \n");
        html.append("<script type=\"text/javascript\"> \r\n ");
        html.append("       jQuery( function(){ \n");
        html.append("            jQuery('#" + id + " .rdetail').click( function(i){ \n");
        html.append("                var id = jQuery(this).parent().parent().attr(\"id\"); \n");
        html.append("                var values = []; \n");
        html.append("                jQuery('#' + id + ' td').each( function(){ \n");
        html.append("                    if( jQuery('.rdetail',this).length == 0 ){ \n");
        html.append("                       var th = jQuery('#' + this.col); \n");
        html.append("                       if( th.attr('detail') != 'false'){ \n");
        html.append("                           var name = th.text(); \n");
        html.append("                           var value = jQuery(this).text(); \n");
        html.append("                           values.push({name:name,value:value}) \n");
        html.append("                       } \n");
        html.append("                    } \n");
        html.append("                }); \n");
        html.append("                window._RowView(values); \n");
        html.append("                jQuery(window).unload(function(){ top.Win.close(); } ); \n");
        html.append("            }); \n");
        html.append("       }); \n");
        html.append("</script>\r\n ");
        return html;
    }

    /**
     * 取得相关参数
     * 
     * @return
     */
    public StringBuffer getParams() {
        StringBuffer html = new StringBuffer(1024);
        html.append("<textarea style='display:none' id='" + context.getTagParamId() + "'>" + param.toString() + "</textarea>\n");
        html.append("<textarea style='display:none' id='" + context.getSqlId() + "'>" + context.getRuntimeSql() + "</textarea>\n");
        html.append("<textarea style='display:none' id='" + context.getRequestParamId() + "'>\n" + context.getRequestParams() + "</textarea>\n");
        return html;
    }
}